<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            border: 1px solid #000;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>

    <script>
        const box = document.getElementById('box')
        let div = {
            offsetX: 0,
            offsetY: 0
        }

        box.onmousedown = (e) => {
            /*
                    用于获取鼠标按下时的坐标
                    按下后，这个值是不会变的
             */


            const evt = window.event;
            div.offsetX = e.clientX
            div.offsetY = e.clientY
            render()
            console.log(e.clientX, e.clientY);


            // console.log("鼠标起始的值：", evt.x);

            window.onmousemove = (e) => {
                // console.log('鼠标移动的值：', e.x);
                div.offsetX = e.x - evt.x
                div.offsetY = e.y - evt.y
                render()
                // console.log("移动的差值:", offsetX);

            }
            window.onmouseup = () => {
                window.onmousemove = null
            }
        }
        const render = () => {
            box.style.left = `${div.offsetX}px`
            box.style.top = `${div.offsetY}px`
        }
    </script>
</body>

</html>